package com.servlet.mail;

import java.util.Properties;
import java.util.Random;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * Classe permettant d'envoyer des emails aux utilisateurs lors de leur inscription
 * ou lorsqu'ils ont perdu leur mot de passe
 * @author Jing Jing
 */
public class SendMail {

	/**
	 * Génère un nouveau mot de passe aléatoire
	 * Méthode utilisée lorsqu'un nouveau mot de passe est généré (si on a perdu son mot de passe)
	 * @return un mot de passe de taille 10 aléatoire
	 */
	public static String generatePasswd() {
		int length = 10;
		String base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		String base2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		String base3 = "0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		int number = random.nextInt(base2.length());
		sb.append(base2.charAt(number));
		number = random.nextInt(base3.length());
		sb.append(base3.charAt(number));
		for (int i = 2; i < length; i++) {
			number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * Envoyer une confirmation d'inscription par email à l'utilisateur qui vient de s'incrire
	 * @param first_name
	 * @param last_name
	 * @param email
	 * @param passwd mot de passe
	 * @return
	 */
	public static boolean sendConfirmation(String first_name, String last_name,String email,String passwd)
	{
		try {
			String host = "smtp.gmail.com";
			String from = "polytech2012";
			String pass = "polytech2012info";
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true"); // added this line
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", pass);
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");

			String[] to = { email }; // added this line

			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));

			InternetAddress[] toAddress = new InternetAddress[to.length];

			// To get the array of addresses
			for (int i = 0; i < to.length; i++) { // changed from a while loop
				toAddress[i] = new InternetAddress(to[i]);
			}

			for (int i = 0; i < toAddress.length; i++) { // changed from a while
															// loop
				message.addRecipient(Message.RecipientType.TO, toAddress[i]);
			}
			message.setSubject("[Propig] Bienvenue sur Propig.net","utf-8");

			String text = "Bonjour "+first_name+" " +last_name +", \n\nVotre compte a bien été créé sur Propig.net et nous vous en remercions !\n\n" 
					+ "Votre identifiant : "+email+"\nVotre mot de passe : "+ passwd+ "\n\nBonne journée et à bientôt,\n\nL'équipe Propig.net";
			message.setText(text,"utf-8");
			Transport transport = session.getTransport("smtp");
			transport.connect(host, from, pass);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

			return true;
		} catch (AddressException e) {
			System.out.println(e.toString());
			return false;
		} catch (MessagingException e) {
			System.out.println(e.toString());
			return false;
		}
	}

	/**
	 * Méthode permettant d'envoyer un nouveau mot de passe à l'utilisateur qui l'a perdu
	 * @param email email de l'utilisateur
	 * @param first_name Prénom de l'utilisateur
	 * @param last_name Nom de l'utilisateur
	 * @param passwd mot de passe de l'utilisateur
	 * @return
	 */
	public static boolean send(String email, String first_name,
			String last_name, String passwd) {
		try {
			String host = "smtp.gmail.com";
			String from = "polytech2012";
			String pass = "polytech2012info";
			Properties props = System.getProperties();
			props.put("mail.smtp.starttls.enable", "true"); // added this line
			props.put("mail.smtp.host", host);
			props.put("mail.smtp.user", from);
			props.put("mail.smtp.password", pass);
			props.put("mail.smtp.port", "587");
			props.put("mail.smtp.auth", "true");

			String[] to = { email }; // added this line

			Session session = Session.getDefaultInstance(props, null);
			MimeMessage message = new MimeMessage(session);
			message.setFrom(new InternetAddress(from));

			InternetAddress[] toAddress = new InternetAddress[to.length];

			// To get the array of addresses
			for (int i = 0; i < to.length; i++) { // changed from a while loop
				toAddress[i] = new InternetAddress(to[i]);
			}

			for (int i = 0; i < toAddress.length; i++) { // changed from a while
															// loop
				message.addRecipient(Message.RecipientType.TO, toAddress[i]);
			}
			message.setSubject("[Propig] Votre nouveau mot de passe", "utf-8");

			String text = "Bonjour " + first_name + " " + last_name
					+ ", \n\nVotre nouveau mot de passe est " + passwd
					+ ".\n\nBonne journée !\n\nL'équipe Propig.net";
			message.setText(text, "utf-8");
			Transport transport = session.getTransport("smtp");
			transport.connect(host, from, pass);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();

			return true;
		} catch (AddressException e) {
			System.out.println(e.toString());
			return false;
		} catch (MessagingException e) {
			System.out.println(e.toString());
			return false;
		}
	}
}
